package com.connector.base.connection.session;

import com.connector.base.cache.CacheKeys;
import com.connector.base.config.InstantConfig;
import com.connector.base.connection.SessionContext;
import com.connector.base.utils.MD5Utils;
import com.google.common.base.Strings;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ResuableSessionManager
{
    private final int expiredTime;
    private final ConcurrentMap<String, String> LOCAL_CACHE;

    public ResuableSessionManager() {
        this.expiredTime = InstantConfig.server.sessionExpiredTime;
        this.LOCAL_CACHE = new ConcurrentHashMap<String, String>();
    }

    public boolean cacheSession(final ResuableSession session) {
        final String key = CacheKeys.getSessionKey(session.getSessionId());
        this.LOCAL_CACHE.putIfAbsent(key, ResuableSession.encode(session.getContext()));
        return true;
    }

    public ResuableSession querySession(final String sessionId) {
        final String key = CacheKeys.getSessionKey(sessionId);
        final String value = this.LOCAL_CACHE.get(key);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return ResuableSession.decode(value);
    }

    public ResuableSession genSession(final SessionContext context) {
        final long now = System.currentTimeMillis();
        final ResuableSession session = new ResuableSession();
        session.setContext(context);
        session.setSessionId(MD5Utils.encrypt(context.getDeviceId() + now));
        session.setExpireTime(now + this.expiredTime * 1000);
        return session;
    }
}
